package com.zqs.grainmall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.zqs.common.to.mq.OrderTo;
import com.zqs.common.to.mq.StockLockedTo;
import com.zqs.grainmall.ware.service.WareSkuService;
import com.zqs.grainmall.ware.vo.OrderVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @program: grain-mall
 * @description:
 * @author: Mr.Zhang
 * @create: 2020-11-28 14:37
 **/
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {

        System.out.println("收到解锁库存的消息...");
        //解锁库存
        try {
            //判断当前消息是否被第二次及以后(重新)派发过来了
           //Boolean redelivered = message.getMessageProperties().getRedelivered();
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e)
        {
            //拒绝消息，把消息重新放到消息队列里面
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo,Message message, Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存...");
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e)
        {
            //拒绝消息，把消息重新放到消息队列里面
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);

        }


    }
}
